

GetMaxKGen = function(ratio, K, Nb){
    
    ### Use dynamic programming to get the maximum ratio against the 
    ### "baseline"
    
    start = cbind(rep(1,Nb), ratio[,"l0","0"], ratio[,"ak",] * cbind(rep(1,Nb), ratio[,"l0","0"]))
    colnames(start) = c("00","10","01","11")
    
    max.ratio = array(NA,c(Nb,K,4))
    dimnames(max.ratio)[[3]] = c("00","10","01","11")
    
    # Choose among l_{k-1},a_{k-1} = "11", "10", "01", "00
    max.ratio[,K,"00"] = pmax(ratio[,"lK","0"] * ratio[,"aK","1"],
                              ratio[,"lK","0"], ratio[,"aK","0"],rep(1,Nb))
    max.ratio[,K,"10"] = pmax(ratio[,"lK","0"] * ratio[,"aK","1"],
                              ratio[,"lK","0"],ratio[,"aK","0"],rep(1,Nb))
    max.ratio[,K,"01"] = pmax(ratio[,"lK","1"] * ratio[,"aK","1"],
                              ratio[,"lK","1"],ratio[,"aK","0"],rep(1,Nb))
    max.ratio[,K,"11"] = pmax(ratio[,"lK","1"] * ratio[,"aK","1"],
                              ratio[,"lK","1"],ratio[,"aK","0"],rep(1,Nb))
    
    for(k in (K-1):1){
        max.ratio[,k,"00"] =
            pmax(ratio[,"lk","0"] * ratio[,"ak","1"] * max.ratio[,k+1,"11"],
                 ratio[,"lk","0"] * max.ratio[,k+1,"10"],
                 ratio[,"ak","0"] * max.ratio[,k+1,"01"],
                 max.ratio[,k+1,"00"])
        max.ratio[,k,"01"] =
            pmax(ratio[,"lk","1"] * ratio[,"ak","1"] * max.ratio[,k+1,"11"],
                 ratio[,"lk","1"] * max.ratio[,k+1,"10"],
                 ratio[,"ak","0"] * max.ratio[,k+1,"01"],
                 max.ratio[,k+1,"00"])
        max.ratio[,k,"10"] =
            pmax(ratio[,"lk","0"] * ratio[,"ak","1"] * max.ratio[,k+1,"11"],
                 ratio[,"lk","0"] * max.ratio[,k+1,"10"],
                 ratio[,"ak","0"] * max.ratio[,k+1,"01"],
                 max.ratio[,k+1,"00"])
        max.ratio[,k,"11"] =
            pmax(ratio[,"lk","1"] * ratio[,"ak","1"] * max.ratio[,k+1,"11"],
                 ratio[,"lk","1"] * max.ratio[,k+1,"10"],
                 ratio[,"ak","0"] * max.ratio[,k+1,"01"],
                 max.ratio[,k+1,"00"])
    }
    
    ratio.max = apply(max.ratio[,1,] * start, 1, max)
    
    return(ratio.max)
    
}